package com.sugar.controller;

import com.sugar.entity.Workers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 商品属性
 *
 * @author felix
 * @email hujinlong18212@gmail.com
 * @date 2024-05-11 20:55:54
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class DataBinderController{

    @InitBinder
    protected void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Date.class,new MyDateEditor());
        // java自带将Double转为字符串的编辑器
        //binder.registerCustomEditor(Double.class,new DoubleEditor());
        // 自定义将web传入String转为Double,后端返回Double转为String
        binder.registerCustomEditor(Double.class,new MyDoubleEditor());
        // java自带将Integer转为字符串的编辑器
        //binder.registerCustomEditor(Double.class,new IntegerEditor());
        // 自定义将web传入String转为Integer,后端返回Integer转为String
        binder.registerCustomEditor(Integer.class,new MyIntegerEditor());

        binder.setDisallowedFields("address");
        log.info("设置值");
    }

    protected class MyDateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = format.parse(text);
            } catch (ParseException e) {
                format = new SimpleDateFormat("yy-MM-dd");
                try {
                    format.parse(text);
                } catch (ParseException ex) {
                    log.error("日期格式转换失败:{}",ex);
                }
            }
            setValue(date);
        }
    }

    protected class MyDoubleEditor extends PropertiesEditor {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Double.parseDouble((text==null||text.equals(""))?"0":text));
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

    protected class MyIntegerEditor extends PropertyEditorSupport{
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Integer.parseInt((text==null||text.equals(""))?"0":text));
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }


    @GetMapping("/test")
    public String Test(){
        return "test";
    }


    @PostMapping("/getWorkersInfo")
    public Workers  getInfo(@ModelAttribute Workers workers){
        return workers;
    }
}
